package com.dangz.dans.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.util.List;

/**
 * EntityServiceImpl JPA 父类实现
 * @author dangz
 * @since 2017/12/28 14:45
 */
public class EntityServiceImpl<T> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired(required = false)
    private LocalContainerEntityManagerFactoryBean emf;
    @Autowired(required = false)
    private EntityManagerFactory em;

    ThreadLocal<EntityManager> managerThreadLocal = new ThreadLocal<>();

    ThreadLocal<EntityManager> sqlManagerThreadLocal = new ThreadLocal<>();

    public List<T> findAll(Class<T> clz){
        logger.info("manager: {}, sqManager: {}", getManager(), getSqlManager());
        try {
            return this.getManager().createQuery("FROM " + clz.getName()).getResultList();
        } finally {
            this.close();
        }

    }

    public EntityManager getManager() {
        EntityManager manager = managerThreadLocal.get();
        if (manager == null) {
            manager = this.em.createEntityManager();
            managerThreadLocal.set(manager);
        }
        return manager;
    }

    public EntityManager getSqlManager() {
        EntityManager manager = sqlManagerThreadLocal.get();
        if (manager == null) {
            manager = this.emf.getNativeEntityManagerFactory().createEntityManager();
            sqlManagerThreadLocal.set(manager);
        }
        return manager;
    }

    public void close(){
        this.getManager().close();
    }

}
